import datetime
import os
import inspect
import ColorPrint


def Return_formatted_string(descript, level, name, time_, pid):
    match level:
        case 'DEBUG':
            LEVEL_FOR_COLOR = ColorPrint.Fore.WHITE
        case 'INFO':
            LEVEL_FOR_COLOR = ColorPrint.Fore.PURPLE
        case 'WARNING':
            LEVEL_FOR_COLOR = ColorPrint.Fore.YELLOW
        case 'ERROR':
            LEVEL_FOR_COLOR = ColorPrint.Fore.RED

    return "{} | {} | {} | {} => {}".format(
        ColorPrint.Return_CPStr(time_.strftime("%Y-%m-%d %H:%M:%S"), forecolor=ColorPrint.Fore.GREEN),
        ColorPrint.Return_CPStr(name, forecolor=ColorPrint.Fore.BLUE),
        ColorPrint.Return_CPStr(pid, forecolor=ColorPrint.Fore.CYAN),
        ColorPrint.Return_CPStr(level, forecolor=LEVEL_FOR_COLOR),
        ColorPrint.Return_CPStr(descript, forecolor=ColorPrint.Fore.WHITE))


def CommonPrintLog(descript, level, name, time_, pid):
    string = Return_formatted_string(descript, level, name, time_, pid)
    print(string)


class Logger(object):
    DEBUG = 0
    INFO = 1
    WARNING = 2
    ERROR = 3

    def __init__(self,
                 # format_=Return_formatted_string,
                 command=[CommonPrintLog],
                 print_level=0):
        """
        :param format -> str:  @value : time            |       CPU 时间
                                        name            |       执行name
                                        pid             |       进程id
                                        level           |       等级
                                        Descript        |       描述
        :param command -> function | List[function] :  执行其中命令， 给予1个参数:
                                                                                String
        """
        self.command = command
        # self.format = format_
        self.print_level = print_level

    def PrintLog(self, descript, level, name, time_=datetime.datetime.now(), pid=os.getpid()):
        if self.print_level > getattr(self, level):
            return
        # string = self.format(descript, level, name, time_, pid)
        for func in self.command:
            func(descript, level, name, time_, pid)

    def info(self, mes):
        name = inspect.stack()[1][3]
        self.PrintLog(mes, 'INFO', name)

    def warning(self, mes):
        name = inspect.stack()[1][3]
        self.PrintLog(mes, 'WARNING', name)

    def debug(self, mes):
        name = inspect.stack()[1][3]
        self.PrintLog(mes, 'DEBUG', name)

    def error(self, mes):
        name = inspect.stack()[1][3]
        self.PrintLog(mes, 'ERROR', name)

    def set_print_level(self, print_level):
        self.print_level = print_level


logger = Logger(print_level=Logger.ERROR)


def main():
    logger.debug('ee')
    logger.info('hh')
    logger.warning('nm')
    logger.error('oh no!')


main()
